<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图书管理系统</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    .book-shelf {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      padding: 20px;
    }
    .book-card {
      width: 180px;
      background: #f8f9fa;
      border-radius: 5px;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      transition: transform 0.3s;
      margin-bottom: 20px;
    }
    .book-card:hover {
      transform: translateY(-5px);
    }
    .book-cover {
      height: 240px;
      background-size: cover;
      background-position: center;
      border-top-left-radius: 5px;
      border-top-right-radius: 5px;
    }
    .book-info {
      padding: 10px;
    }
    .book-title {
      font-weight: bold;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .book-author {
      color: #6c757d;
      font-size: 0.9em;
    }
    .book-price {
      color: #dc3545;
      font-weight: bold;
    }
    .book-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
    }
    .table-cover-img {
      width: 60px;
      height: 80px;
      object-fit: cover;
    }
    #show_page_info {
      line-height: 80px;
    }
  </style>
</head>
<body>
<div class="container mt-4">
  <h1 class="text-center mb-4">图书管理系统</h1>

  <!-- 搜索和添加区域 -->
  <div class="row mb-4">
    <div class="col-md-9">
      <div class="row">
        <div class="col-md-5 mb-2">
          <input type="text" class="form-control" id="bookNameSearch" placeholder="书籍名称">
        </div>
        <div class="col-md-5 mb-2">
          <input type="text" class="form-control" id="authorSearch" placeholder="作者">
        </div>
        <div class="col-md-2">
          <button class="btn btn-danger w-100" onclick="queryBook(1)">搜索</button>
        </div>
      </div>
    </div>
    <div class="col-md-3">
      <button class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#addBookModal">
        添加图书
      </button>
    </div>
  </div>

  <!-- 书架视图 -->
  <div class="book-shelf" id="bookShelfView"></div>

  <!-- 表格视图 -->
  <table class="table table-bordered text-center" id="tableView" style="display:none;">
    <thead>
    <tr>
      <th>编号</th>
      <th>书籍名称</th>
      <th>作者</th>
      <th>价格</th>
      <th>书籍类型</th>
      <th>封面</th>
      <th>出版日期</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody id="showMessage"></tbody>
  </table>

  <!-- 分页控制区域 -->
  <div class="row mt-3">
    <div class="col-md-6">
      <button id="toggleView" class="btn btn-info">切换视图</button>
    </div>
    <div id="show_page_info" class="col-md-3"></div>
    <div class="col-md-3">
      <nav aria-label="Page navigation" class="float-end">
        <ul class="pagination" id="pagination">
          <li class="page-item" id="prevPage">
            <a class="page-link" href="javascript:void(0);" aria-label="Previous">
              <span aria-hidden="true">&laquo;</span>
            </a>
          </li>
          <li class="page-item" id="nextPage">
            <a class="page-link" href="javascript:void(0);" aria-label="Next">
              <span aria-hidden="true">&raquo;</span>
            </a>
          </li>
        </ul>
      </nav>
    </div>
  </div>
</div>

<!-- 添加图书模态框 -->
<div class="modal fade" id="addBookModal" tabindex="-1" aria-labelledby="addBookModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addBookModalLabel">添加新图书</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="bookAddForm" enctype="multipart/form-data">
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label">书籍名称</label>
                <input type="text" class="form-control" name="bookName" required>
              </div>
              <div class="mb-3">
                <label class="form-label">作者</label>
                <input type="text" class="form-control" name="author" required>
              </div>
              <div class="mb-3">
                <label class="form-label">出版日期</label>
                <input type="date" class="form-control" name="publicationDate">
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label">价格</label>
                <input type="text" class="form-control" name="price" required>
              </div>
              <div class="mb-3">
                <label class="form-label">书籍类型</label>
                <select class="form-select" name="bookTypeId" required>
                  <option value="">请选择书籍类型</option>
                </select>
              </div>
              <div class="mb-3">
                <label class="form-label">封面图片</label>
                <input type="file" class="form-control" name="bookImageFile" accept="image/*">
              </div>
              <div class="mb-3">
                <img id="showPic" src="" class="img-thumbnail" style="max-height: 200px;">
              </div>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" onclick="addBook()">添加图书</button>
      </div>
    </div>
  </div>
</div>

<!-- 编辑图书模态框 -->
<div class="modal fade" id="editBookModal" tabindex="-1" aria-labelledby="editBookModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editBookModalLabel">修改图书信息</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="editBookForm" enctype="multipart/form-data">
          <input type="hidden" name="id" id="editBookId">
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label">书籍名称</label>
                <input type="text" class="form-control" name="bookName" id="editBookName" required>
              </div>
              <div class="mb-3">
                <label class="form-label">作者</label>
                <input type="text" class="form-control" name="author" id="editAuthor" required>
              </div>
              <div class="mb-3">
                <label class="form-label">出版日期</label>
                <input type="date" class="form-control" name="publicationDate" id="editPublicationDate">
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label">价格</label>
                <input type="text" class="form-control" name="price" id="editPrice" required>
              </div>
              <div class="mb-3">
                <label class="form-label">书籍类型</label>
                <select class="form-select" name="bookTypeId" id="editBookType" required>
                  <option value="">请选择书籍类型</option>
                </select>
              </div>
              <div class="mb-3">
                <label class="form-label">封面图片</label>
                <input type="file" class="form-control" name="bookImageFile" accept="image/*">
              </div>
              <div class="mb-3">
                <img id="editCoverImage" src="" class="img-thumbnail" style="max-height: 200px;">
              </div>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" onclick="updateBook()">保存更改</button>
      </div>
    </div>
  </div>
</div>

<script>
  // 全局变量
  let currentView = 'shelf'; // shelf 或 table
  let currentPage = 1;
  let totalPages = 1;

  // 页面加载完成后执行
  $(document).ready(function() {
    loadBookTypes();
    queryBook(1);

    // 预览上传的图片
    $('input[name="bookImageFile"]').on('change', function(e) {
      const file = e.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = function(event) {
          const imgId = $(e.target).closest('form').attr('id') === 'bookAddForm' ? '#showPic' : '#editCoverImage';
          $(imgId).attr('src', event.target.result);
        };
        reader.readAsDataURL(file);
      }
    });

    // 切换视图
    $('#toggleView').click(function() {
      if (currentView === 'shelf') {
        $('#bookShelfView').hide();
        $('#tableView').show();
        currentView = 'table';
        $(this).text('切换到书架视图');
      } else {
        $('#tableView').hide();
        $('#bookShelfView').show();
        currentView = 'shelf';
        $(this).text('切换到表格视图');
      }
    });

    // 上一页按钮点击事件
    $('#prevPage').click(function() {
      if (currentPage > 1) {
        queryBook(currentPage - 1);
      }
    });

    // 下一页按钮点击事件
    $('#nextPage').click(function() {
      if (currentPage < totalPages) {
        queryBook(currentPage + 1);
      }
    });
  });

  // 加载书籍类型
  function loadBookTypes() {
    $.ajax({
      url: "http://localhost:25080/book/api/bookTypes/getAllBookTypes",
      type: "GET",
      success: function(data) {
        const $addSelect = $('#bookAddForm select[name="bookTypeId"]');
        const $editSelect = $('#editBookForm select[name="bookTypeId"]');

        $addSelect.empty().append('<option value="">请选择书籍类型</option>');
        $editSelect.empty().append('<option value="">请选择书籍类型</option>');

        $.each(data, function(index, type) {
          $addSelect.append(`<option value="${type.id}">${type.typeName}</option>`);
          $editSelect.append(`<option value="${type.id}">${type.typeName}</option>`);
        });
      },
      error: function(xhr, status, error) {
        console.error("获取书籍类型失败:", error);
        alert("获取书籍类型失败，请刷新页面重试");
      }
    });
  }

  // 查询书籍
  function queryBook(pageNum) {
    currentPage = pageNum;

    const bookDTO = {
      bookName: $("#bookNameSearch").val(),
      author: $("#authorSearch").val(),
      pageNum: pageNum,
      pageSize: 4
    };

    $.ajax({
      url: "http://localhost:25080/book/api/book/getBook",
      type: "POST",
      contentType: "application/json",
      data: JSON.stringify(bookDTO),
      success: function(response) {
        console.log("响应数据:", response);

        // 更新表格和书架视图
        renderBookTable(response.data.data);
        renderBookShelf(response.data.data);

        // 更新分页信息
        updatePageInfo(response.data);

        // 更新分页按钮状态
        updatePaginationButtons(response.data);
      },
      error: function(xhr, status, error) {
        console.error("请求失败:", error);
        alert("加载数据失败，请重试");
      }
    });
  }

  // 渲染表格视图
  function renderBookTable(books) {
    const $tableBody = $('#showMessage');
    $tableBody.empty();

    $.each(books, function(index, book) {
      $tableBody.append(`
        <tr>
          <td>${book.id}</td>
          <td>${book.bookName}</td>
          <td>${book.author}</td>
          <td>${book.price}</td>
          <td>${book.bookTypes?.typeName || '无类型'}</td>
          <td><img src="http://localhost:25080/book/uploads/${book.coverImageUrl}" class="table-cover-img"></td>
          <td>${book.publicationDate}</td>
          <td>
            <button class="btn btn-primary btn-sm" onclick="editBook(${book.id})">编辑</button>
            <button class="btn btn-danger btn-sm" onclick="deleteBook(${book.id})">删除</button>
          </td>
        </tr>
      `);
    });
  }

  // 渲染书架视图
  function renderBookShelf(books) {
    const $shelfView = $('#bookShelfView');
    $shelfView.empty();

    $.each(books, function(index, book) {
      $shelfView.append(`
        <div class="book-card">
          <div class="book-cover" style="background-image: url('http://localhost:25080/book/uploads/${book.coverImageUrl}')"></div>
          <div class="book-info">
            <div class="book-title">${book.bookName}</div>
            <div class="book-author">${book.author}</div>
            <div class="book-price">¥${book.price}</div>
            <div class="book-actions">
              <button class="btn btn-primary btn-sm" onclick="editBook(${book.id})">编辑</button>
              <button class="btn btn-danger btn-sm" onclick="deleteBook(${book.id})">删除</button>
            </div>
          </div>
        </div>
      `);
    });
  }

  // 更新分页信息
  function updatePageInfo(pageData) {
    currentPage = pageData.pageNum;
    totalPages = pageData.totalPage;
    $('#show_page_info').text(`当前第${currentPage}页 / 共${totalPages}页`);
  }

  // 更新分页按钮状态
  function updatePaginationButtons(pageData) {
    console.log(pageData.pageNum, pageData.totalPage)
    // 上一页按钮
    if (pageData.pageNum < 1) {

      $('#prevPage').addClass('disabled');
    } else {
      $('#prevPage').removeClass('disabled');
    }

    // 下一页按钮
    if (pageData.pageNum > pageData.totalPage) {

      $('#nextPage').addClass('disabled');
    } else {
      $('#prevPage').removeClass('disabled');

    }
  }

  // 添加图书
  function addBook() {
    const formData = new FormData(document.getElementById('bookAddForm'));

    // 验证必填字段
    if (!formData.get('bookName') || !formData.get('author') ||
            !formData.get('price') || !formData.get('bookTypeId') ||
            !formData.get('bookImageFile')) {
      alert('请填写所有必填字段');
      return;
    }

    $.ajax({
      url: "http://localhost:25080/book/api/book/addBook",
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function(response) {
        alert('添加成功');
        $('#addBookModal').modal('hide');
        queryBook(1);
      },
      error: function(xhr, status, error) {
        console.error("添加失败:", error);
        alert("添加失败: " + xhr.responseText);
      }
    });
  }

  // 编辑图书
  function editBook(id) {
    $.ajax({
      url: `http://localhost:25080/book/api/book/getBookById?id=${id}`,
      type: "GET",
      success: function(book) {
        // 填充表单数据
        $('#editBookId').val(book.data.id);
        $('#editBookName').val(book.data.bookName);
        $('#editAuthor').val(book.data.author);
        $('#editPrice').val(book.data.price);
        $('#editBookType').val(book.data.bookTypeId);
        $('#editPublicationDate').val(book.data.publicationDate);

        // 显示封面图片
        $('#editCoverImage').attr('src', `http://localhost:25080/book/uploads/${book.data.coverImageUrl}`);

        // 显示模态框
        $('#editBookModal').modal('show');
      },
      error: function(xhr, status, error) {
        console.error("获取图书信息失败:", error);
        alert("获取图书信息失败，请重试");
      }
    });
  }

  // 更新图书
  function updateBook() {
    const formData = new FormData(document.getElementById('editBookForm'));

    // 验证必填字段
    if (!formData.get('bookName') || !formData.get('author') ||
            !formData.get('price') || !formData.get('bookTypeId')) {
      alert('请填写所有必填字段');
      return;
    }

    $.ajax({
      url: "http://localhost:25080/book/api/book/updateBook",
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      success: function(response) {
        alert('更新成功');
        $('#editBookModal').modal('hide');
        queryBook(currentPage);
      },
      error: function(xhr, status, error) {
        console.error("更新失败:", error);
        alert("更新失败: " + xhr.responseText);
      }
    });
  }

  // 删除图书
  function deleteBook(id) {
    if (!confirm('确定要删除这本书吗？')) return;

    $.ajax({
      url: `http://localhost:25080/book/api/book/deleteBook?id=${id}`,
      type: "DELETE",
      success: function(response) {
        alert('删除成功');
        queryBook(currentPage);
      },
      error: function(xhr, status, error) {
        console.error("删除失败:", error);
        alert("删除失败: " + xhr.responseText);
      }
    });
  }
</script>
</body>
</html>